#!/bin/bash
#shellcheck disable=SC2312

# Set Variables
MCS_INSTALL_BIN=/usr/bin
LOG_PREFIX=/var/log/mariadb/columnstore
PROGS='DMLProc DDLProc WriteEngineServer PrimProc workernode controllernode StorageManager'
CMAPI_PID=$(pgrep -f 'python3 -m cmapi_server')
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

stop_mcs_processes() {
    echo "$(date)": Stopping... >> "${LOG_PREFIX}"/mcs-start.log
    
    if  [[ -n $(pidof ${PROGS}) ]]; then
        # Save BRM on the primary node only
        if  [[ -n "$(pidof controllernode)" ]]; then
            "${MCS_INSTALL_BIN}"/mcs-savebrm.py &>> "${LOG_PREFIX}"/savebrm.log
        fi
        echo "$(date)": Sending SIGTERM >> "${LOG_PREFIX}"/mcs-start.log
        for PID in $(pidof ${PROGS});
        do
            kill "${PID}" &> /dev/null
        done
        sleep 3
        # Make sure StorageManager had a chance to shutdown cleanly
        counter=1
        while [[ -n "$(pidof StorageManager)" && ${counter} -le 60 ]]
        do
            sleep 1
            ((counter++))
        done
        echo "$(date)": Sending SIGKILL >> "${LOG_PREFIX}"/mcs-start.log
        for PID in $(pidof ${PROGS});
        do
            kill -9 "${PID}" &> /dev/null
        done
        echo "$(date)": Clearing SHM >> "${LOG_PREFIX}"/mcs-start.log
        "${MCS_INSTALL_BIN}"/clearShm
    fi
}

# Stop CMAPI
if [[ -n ${CMAPI_PID} ]]; then
    if kill "${CMAPI_PID}" &> /dev/null; then
        echo -e "Stopping Cluster Manager API... ${GREEN}done${NC}"
    else
        echo -e "Stopping Cluster Manager API... ${RED}fail${NC}"
        exit 1
    fi
fi

# Stop Columnstore
if [[ -n $(pidof ${PROGS}) ]]; then
    if stop_mcs_processes &> /dev/null; then
        echo -e "Stopping ColumnStore Processes... ${GREEN}done${NC}"
    else
        echo -e "Stopping ColumnStore Processes... ${RED}fail${NC}"
    fi
fi

# Stop MariaDB
if mariadb-admin ping &> /dev/null; then
    if /etc/init.d/mariadb stop &> /dev/null; then
        echo -e "Stopping MariaDB Server... ${GREEN}done${NC}"
    else
        echo -e "Stopping MariaDB Server... ${RED}fail${NC}"
        exit 1
    fi
fi